﻿using QuanLyGiaoVuDAL.DTO;
using QuanLyGiaoVuService.CommandServices;
using QuanLyGiaoVuService.CommonServices;
using QuanLyGiaoVuService.ReportServices;
using QuanLyGiaoVuUI.Extensions.ExtendedAttributes;
using QuanLyGiaoVuUI.Extensions.Utilities;
using QuanLyGiaoVuUI.Models;
using QuanLyGiaoVuUI.Models.TaiLieu;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QuanLyGiaoVuUI.Controllers
{
    [GiangVienAuthorize]
    public class TaiLieuGiangVienController : Controller
    {
        //
        // GET: /TaiLieuGiangVien/
        private ITaiLieuReportService _taiLieuReportService;
        private ITaiLieuCommandService _taiLieuCommandService;
        private IFileService _fileService;
        private IQuanLyQuyenTruyCapService _quyenTruyCapService;
        private IThamSoService _thamSoService;
        private IGiangVienReportService _giangVienReportService;

        public TaiLieuGiangVienController(ITaiLieuReportService taiLieuReportService,
            ITaiLieuCommandService taiLieuCommandService,
            IFileService fileService,
            IQuanLyQuyenTruyCapService quyenTruyCapService,
            IThamSoService thamSoService,
            IGiangVienReportService giangVienReportService
            )
        {
            _taiLieuReportService = taiLieuReportService;
            _taiLieuCommandService = taiLieuCommandService;
            _fileService = fileService;
            _quyenTruyCapService = quyenTruyCapService;
            _thamSoService = thamSoService;
            _giangVienReportService = giangVienReportService;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult ChonThuMucDialog(Guid? maThuMucCha)
        {
            ViewData["maThuMucCha"] = maThuMucCha;
            return View();
        }

        [HttpGet]
        public JsonResult GetThuMuc(Guid? maThuMucCha)
        {
            bool isRoot = false;
            if (maThuMucCha == null)
            {
                Guid maThuMucChaGiangVien;
                if (Guid.TryParse(_thamSoService.GetThamSo("MaThuMucGocGiangVien"), out maThuMucChaGiangVien))
                {
                    maThuMucCha = maThuMucChaGiangVien;
                    isRoot = true;
                }
            }
            List<ThuMucDTO> danhSachThuMuc = _taiLieuReportService.GetAllThuMucByMaThuMucCha(maThuMucCha).ToList();
            if (isRoot)
            {
                danhSachThuMuc = danhSachThuMuc.Where(thuMuc => thuMuc.MaThuMuc == UserUtility.GetCurrentUser().MaNguoiDung).ToList();
                if (danhSachThuMuc.Count() == 0)
                {
                    Guid maAdmin;
                    Guid.TryParse(_thamSoService.GetThamSo("MaAdmin"), out maAdmin);
                    ThuMucDTO thuMucGoc = new ThuMucDTO();
                    var giangVien = _giangVienReportService.GetGiangVienById(UserUtility.GetCurrentUser().MaNguoiDung);
                    thuMucGoc.MaThuMucCha = maThuMucCha;
                    thuMucGoc.TenThuMuc = giangVien.GetTenVaHocVi();
                    _taiLieuCommandService.TaoThuMucGocGiangVien(maAdmin,giangVien.ID, thuMucGoc);
                    danhSachThuMuc.Add(thuMucGoc);
                }
            }
            //List<ThuMucDTO> danhSachThuMuc=_taiLieuReportService.            
            //IEnumerable<TaiLieuDTO> dsTaiLieu = _taiLieuReportService.GetAllTaiLieu(null, null, gvid, null);

            List<JsTreeNode> nodesList = new List<JsTreeNode>();
            foreach (ThuMucDTO thuMuc in danhSachThuMuc)
            {
                JsTreeNode node = new JsTreeNode();
                node.attr = new Attributes();
                node.attr.id = thuMuc.MaThuMuc.ToString();
                node.attr.rel = "folder";
                node.data = thuMuc.TenThuMuc;
                node.state = "closed";
                nodesList.Add(node);
            }
            return Json(nodesList.ToArray(), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult TaoThuMuc()
        {
            TaoThuMucViewModel viewModel = new TaoThuMucViewModel();
            viewModel.DanhSachThuMuc = _taiLieuReportService.GetThuMuc(null);
            return View(viewModel);
        }

        [HttpPost]
        public JsonResult TaoThuMuc(TaoThuMucViewModel viewModel)
        {
            object jsonData;
            if (ModelState.IsValid)
            {
                NguoiDungDTO myInfo = new NguoiDungDTO();
                if (Session["UserInfo"] != null)
                {
                    myInfo = (NguoiDungDTO)Session["UserInfo"];
                }
                _taiLieuCommandService.TaoThuMucMoi(myInfo.MaNguoiDung, viewModel.ToThuMucDTO());
                jsonData = new
                {
                    success = true,
                    message = "Tạo thư mục thành công!"
                };
            }
            else jsonData = new
            {
                success = false,
                message = "Tạo thư mục không thành công!"
            };
            return Json(jsonData);
        }

        [HttpPost]
        public JsonResult DoiTenThuMuc(Guid? maThuMuc, String tenThuMuc)
        {
            if (maThuMuc != null)
            {
                NguoiDungDTO myInfo = new NguoiDungDTO();
                if (Session["UserInfo"] != null)
                {
                    myInfo = (NguoiDungDTO)Session["UserInfo"];
                }
                    ThuMucDTO thuMuc = _taiLieuReportService.GetThuMuc(maThuMuc).First();
                    thuMuc.TenThuMuc = tenThuMuc;
                    _taiLieuCommandService.SuaThuMuc(myInfo.MaNguoiDung, thuMuc);
                    return Json(new { success = true });
            }
            return Json(new { success = false });
        }

        [HttpPost]
        public JsonResult XoaThuMuc(Guid? maThuMuc)
        {
            string message = string.Empty;
            try
            {
                if (maThuMuc != null)
                {
                    NguoiDungDTO myInfo = new NguoiDungDTO();
                    if (Session["UserInfo"] != null)
                    {
                        myInfo = (NguoiDungDTO)Session["UserInfo"];
                    }
                    if (_taiLieuCommandService.XoaThuMuc(myInfo.MaNguoiDung, (Guid)maThuMuc))
                        return Json(new { success = true });
                    else
                        message = "Xóa thư mục không thành công.";
                }
                else
                    message = "";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return Json(new
            {
                success = false,
                message = message
            });
        }

        [HttpGet]
        public ActionResult GetCayThuMuc(Guid? maThuMucCha)
        {
            return PartialView("CayThuMuc");
        }

        [HttpGet]
        public ActionResult TaoTaiLieu(Guid? maTaiLieu, Guid? maThuMucCha)
        {
            CapNhatTaiLieuViewModel viewModel = new CapNhatTaiLieuViewModel();
            if (maTaiLieu != null)
            {
                viewModel = CapNhatTaiLieuViewModel.FromTaiLieuDTO(_taiLieuReportService.GetTaiLieuById((Guid)maTaiLieu));
                maThuMucCha = viewModel.MaThuMuc;
            }
            viewModel.DanhSachThuMuc = _taiLieuReportService.GetThuMuc(null);
            viewModel.DanhSachLoaiTaiLieu = _taiLieuReportService.GetLoaiTaiLieu(null);
            ViewData["maThuMucCha"] = maThuMucCha ?? Guid.Empty;
            ViewData["duongDanThuMuc"] = maThuMucCha != null ? _taiLieuReportService.GetDuongDanThuMuc((Guid)maThuMucCha) : String.Empty;
            return View(viewModel);
        }

        [HttpGet]
        public JsonResult GetDuongDanThuMuc(Guid maThuMuc)
        {
            string duongDan = _taiLieuReportService.GetDuongDanThuMuc(maThuMuc);
            return Json(new { duongDan = duongDan }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult TaoTaiLieu(CapNhatTaiLieuViewModel viewModel)
        {
            object jsonData;

            if (ModelState.IsValid)
            {
                NguoiDungDTO myInfo = new NguoiDungDTO();
                if (Session["UserInfo"] != null)
                {
                    myInfo = (NguoiDungDTO)Session["UserInfo"];
                }
                viewModel.PhanMoRong = Path.GetExtension(viewModel.TenTapTin);
                viewModel.TenTapTin = Path.GetFileNameWithoutExtension(viewModel.TenTapTin);
                if (viewModel.MaTaiLieu.Equals(Guid.Empty))
                {
                    _taiLieuCommandService.InsertTaiLieu(myInfo.MaNguoiDung, viewModel.ToTaiLieuDTO());
                }
                else
                {
                    _taiLieuCommandService.UpdateTaiLieu(myInfo.MaNguoiDung, viewModel.ToTaiLieuDTO());
                }
                jsonData = new
                {
                    success = true,
                    message = "Tạo tài liệu thành công!"
                };
            }
            else jsonData = new
            {
                success = false,
                message = "Tạo tài liệu không thành công!"
            };
            return Json(jsonData);
        }

        [HttpPost]
        public JsonResult XoaTaiLieu(Guid? maTaiLieu)
        {
            object jsonResult;
            string message = string.Empty;
            try
            {
                if (maTaiLieu != null)
                {
                    NguoiDungDTO myInfo = new NguoiDungDTO();
                    if (Session["UserInfo"] != null)
                    {
                        myInfo = (NguoiDungDTO)Session["UserInfo"];
                    }
                    var tailieu = _taiLieuReportService.GetTaiLieuById((Guid)maTaiLieu);
                    var maTapTin = tailieu.MaTapTin;
                    _taiLieuCommandService.DeleteTaiLieu(myInfo.MaNguoiDung, (Guid)maTaiLieu);
                    _fileService.DeleteFileById(maTapTin);

                    jsonResult = new
                    {
                        success = true
                    };
                }
                else
                    jsonResult = new
                    {
                        success = false,
                        message = "Không thể xóa loại tài liệu này."
                    };
            }
            catch (Exception exception)
            {
                jsonResult = new
                {
                    success = false,
                    message = exception.Message
                };
            }
            return Json(jsonResult);
        }

        [HttpPost]
        public JsonResult UpLoadFile()
        {
            object jsonData;
            HttpPostedFileBase file = Request.Files[0];

            if (ModelState.IsValid && file != null)
            {
                Guid maTapTin = Guid.Empty;
                _fileService.SaveFileFromStream(null, file.InputStream, file.FileName, file.ContentType, out maTapTin);
                jsonData = new
                {
                    success = true,
                    fileName = file.FileName,
                    fileSize = file.ContentLength,
                    fileId = maTapTin
                };
            }
            else jsonData = new
            {
                success = false,
                message = "Tạo tài liệu không thành công!"
            };
            return Json(jsonData);
        }

        [HttpPost]
        public JsonResult SaoChepTaiLieu(Guid? maTaiLieu, Guid? maThuMuc)
        {
            if (maTaiLieu.HasValue && maThuMuc.HasValue)
            {
                _taiLieuCommandService.SaoChepTaiLieu((Guid)maTaiLieu, (Guid)maThuMuc);
                return Json(new { 
                    success = true
                });
            }
            else
                return Json(new
                {
                    success = false,
                    message = "Tài liệu hoặc thư mục không tồn tại."
                });

        }

        [HttpGet]
        public PartialViewResult LayDanhSachTaiLieu(Guid? thuMucHienTai)
        {
            IEnumerable<DanhSachTaiLieuViewModel> danhSachTaiLieu = new List<DanhSachTaiLieuViewModel>();
            if (thuMucHienTai != null && !thuMucHienTai.Equals(Guid.Empty))
            {
                ViewData["ChiaSe"] = false;
                danhSachTaiLieu = DanhSachTaiLieuViewModel.FromTaiLieuDTOList(_taiLieuReportService.GetAllTaiLieu(thuMucHienTai, null, null, null, null));
            }
            return PartialView("DanhSachTaiLieuGrid", danhSachTaiLieu);
        }

        [HttpGet]
        public ActionResult TaiFile(Guid? fileId)
        {
            Stream fileStream;
            String fileName;
            String contentType;
            if (fileId == null || !_fileService.GetFileStreamById((Guid)fileId, out fileStream, out fileName, out contentType))
                return new HttpNotFoundResult("File not found!");
            Response.BufferOutput = false;
            FileStreamResult fileStreamResult = new FileStreamResult(fileStream, contentType)
            {
                FileDownloadName = fileName
            };
            return fileStreamResult;
        }

        [HttpGet]
        public ActionResult KhoTaiLieuChiaSe()
        {
            return View();
        }

        [HttpGet]
        public ActionResult LayDanhSachTaiLieuChiaSe()
        {
            IEnumerable<DanhSachTaiLieuViewModel> danhSachTaiLieu = new List<DanhSachTaiLieuViewModel>();
            danhSachTaiLieu = DanhSachTaiLieuViewModel.FromTaiLieuDTOList(_taiLieuReportService.GetAllTaiLieu(null, null, null, null, true));
            ViewData["ChiaSe"] = true;
            return PartialView("DanhSachTaiLieuGrid", danhSachTaiLieu);
        }

        [HttpPost]
        public ActionResult ChiaSeTaiLieu(Guid maTaiLieu, bool chiaSe)
        {
            try
            {
                if (_taiLieuCommandService.ChiaSeTaiLieu(maTaiLieu, chiaSe))
                {
                    return Json(new JsonResultObject(true, string.Empty));
                }
                else
                    return Json(new JsonResultObject(false, "Không thể chia sẻ/tắt chia sẻ tài liệu."));
            }
            catch (Exception exception)
            {
                return Json(new JsonResultObject(false, exception.Message));
            }
        }

        Guid AdminId
        {
            get
            {
                Guid adminId;
                if (Guid.TryParse("2d700c4c-00e4-495d-a8d6-1d1619728d1f", out adminId))
                    return adminId;
                else
                    return Guid.Empty;
            }
        }
    }
}
